package com.mc.test.dao.impl;

import java.io.Serializable;
import java.util.List;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import com.google.common.base.Preconditions;
import com.mc.test.dao.IGenericDAO;

@Repository
public abstract class GenericHibernateDAO<T,ID extends Serializable, DAOImpl extends IGenericDAO<T,ID>> implements IGenericDAO<T,ID> {

	private Class<T> clazz;

	@Autowired
	SessionFactory sessionFactory;

	public void setClazz(final Class<T> clazzToSet) {
		this.clazz = clazzToSet;
	}

	public T findById(final Long id) {
		Preconditions.checkArgument(id != null);
		return (T) this.getCurrentSession().get(this.clazz, id);
	}

	public List<T> findAll() {
		return this.getCurrentSession()
				.createQuery("from User").list();
	}

	public void create(final T entity) {
		Preconditions.checkNotNull(entity);
		this.getCurrentSession().persist(entity);
	}

	public void update(final T entity) {
		Preconditions.checkNotNull(entity);
		this.getCurrentSession().merge(entity);
	}

	public void delete(final T entity) {
		Preconditions.checkNotNull(entity);
		this.getCurrentSession().delete(entity);
	}

	public void deleteById(final Long entityId) {
		final T entity = this.findById(entityId);
		Preconditions.checkState(entity != null);
		this.delete(entity);
	}

	protected final Session getCurrentSession() {
		return this.sessionFactory.getCurrentSession();
	}

	
}
